/*
  Pachube sensor client
  
  Monitor temperature locally and send it to pachube.com
 
 

 based off of: 
 http://www.tigoe.net/pcomp/code/category/arduinowiring/873
 
 */

#include <SPI.h>
#include <Ethernet.h>

// assign a MAC address for the ethernet controller.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
// fill in your address here:
byte mac[] = { 
  0x90, 0xA2, 0xDA, 0x00, 0xF6, 0x3A};

// initialize the library instance:
EthernetClient client;

long lastConnectionTime = 0;        // last time you connected to the server, in milliseconds
boolean lastConnected = false;      // state of the connection last time through the main loop
const int postingInterval = 60000;  //delay between updates to Pachube.com


const String pachubeKey = "sc1W7fiShkAo-5m7U6xCaYN1rMESNog2K5FkEyTT41kc5uVv3PKqVaTHa0I1-g5JeT7BnbmuAxZACaxTk-yJHpFohPF9MSvRFzy9IfD2xcQGcLyHMe-wuHwoXUzOaehV7ZBFdf6PZZo82-t2aDRQXA";
const String feedId = "42739";
const String pachubeHost = "api.pachube.com";
//const String pachubeHost = "Amazonia";
//IPAddress pachubeHost(173,194,67,105); // pachube

void setup() {
  // start serial port:
  Serial.begin(9600);
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP.  Permanent fail on startup - Looping for ever...");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP.  Permanent fail DHCP - Looping for ever...");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
}

void loop() {
  // read the analog sensor:
  int sensorReading = 21;   

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    sendData("{\"version\":\"1.0.0\",\"datastreams\":[{\"id\":\"DiningRoomTemp\",\"current_value\":\"21.0\"}]}");
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:
void sendData(String thisData) {
  
  
  char pachubeHostChar[pachubeHost.length()];
 pachubeHost.toCharArray(pachubeHostChar, pachubeHost.length());
 
 int connectResult = client.connect(pachubeHostChar, 80);
  // if there's a successful connection:
  //if (client.connect("api.pachube.com", 80)) 
  if (connectResult) 
  {
    Serial.println("connecting... to " + pachubeHost);

    // calculate the length of the sensor reading in bytes:
    int thisLength = thisData.length();
    
    String dataLength = "";
    dataLength += thisLength;
    Serial.println(dataLength);

    sendLine("PUT http://" + pachubeHost + "/v2/feeds/" + feedId + " HTTP/1.1");       
    sendLine("Host: " + pachubeHost);   
    sendLine("Accept: *//*");
    sendLine("Connection: Keep-Alive");
    sendLine("X-PachubeApiKey: " + pachubeKey);
    sendLine("Content-Length: " + dataLength);    
    //sendLine("Content-Type: application/json; charset=utf-8");    
    
    // here's the actual content of the PUT request:
    sendLine(thisData);
    client.println();
    client.println();

    /*
    sendLine("GET /v2/feeds/" + feedId + " HTTP/1.1");       
    //sendLine("Host: " + pachubeHost);   
    //sendLine("Connection: close");
    //sendLine("X-PachubeApiKey: " + pachubeKey);    
*/
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed, return was : " + connectResult);
    
    //Delay to reduce swamping with retries
    delay(2000);
  }
}

void sendLine(String value)
{
    Serial.println(value);
    client.println(value);
}
